package cn.com.wdjedu.androidapp.wjeduandroid;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.Constanct;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.DeletableEditText;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.MyGifView;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Login extends Activity {

    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.tv_psd)
    DeletableEditText tvPsd;
    @BindView(R.id.login_forget)
    TextView loginForget;
    @BindView(R.id.login_register)
    TextView loginRegister;
    @BindView(R.id.tv_user)
    DeletableEditText tvUser;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.login_form)
    ScrollView loginForm;
    @BindView(R.id.rememberCheck)
    CheckBox rememberCheck;
    @BindView(R.id.sheep_gif)
    MyGifView sheepGif;
    @BindView(R.id.textViewLoading)
    TextView textViewLoading;
    @BindView(R.id.login_container)
    RelativeLayout loginContainer;


    private UserLoginTask mAuthTask = null;
    //请求超时时更新线程
    private Runnable updateThread_Overtime;

    //记住密码
    private SharedPreferences sp;
    private String phoneValue, passwordValue;

    //计时器
    private CountDownTimer timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login2);
        ButterKnife.bind(this);

        initView();
    }

    public void initView() {

        //记住密码的设置
        sp = getApplicationContext().getSharedPreferences("userInfo", Context.MODE_WORLD_READABLE);
        if (sp.getBoolean("ISCHECK", false)) {
            rememberCheck.setChecked(true);
            tvUser.setText(sp.getString("USER_NAME", ""));
            tvPsd.setText(sp.getString("PASSWORD", ""));
        }

        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attemptLogin();

                //登录时记住密码
                phoneValue = tvUser.getText().toString();
                passwordValue = tvPsd.getText().toString();
                SharedPreferences.Editor editor = sp.edit();
                if (rememberCheck.isChecked()) {
                    editor.putString("USER_NAME", phoneValue);
                    editor.putString("PASSWORD", passwordValue);
                } else {
                    editor.putString("USER_NAME", phoneValue);
                    editor.putString("PASSWORD", "");
                }
                editor.commit();
                //登录时记住密码
            }
        });

        rememberCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (rememberCheck.isChecked()) {
                    sp.edit().putBoolean("ISCHECK", true).commit();
                } else {
                    sp.edit().putBoolean("ISCHECK", true).commit();
                }
            }
        });

        loginRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplication(), RegistActivity.class);
                i.putExtra("type", "register");
                startActivity(i);
//                finish();
            }
        });

        loginForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplication(), RegistActivity.class);
                i.putExtra("type", "reset");
                startActivity(i);
            }
        });

        loginForm.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                    showProgress(false);
                    mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                    mAuthTask = null;
                    timer.cancel();
                }
                return true;
            }
        });

        //请求超时时更新线程
        updateThread_Overtime = new Runnable() {
            @Override
            public void run() {
                try {
                    //更新UI
                    Toast.makeText(getApplicationContext(), "请求超时,请检查网络", Toast.LENGTH_SHORT).show();
                    if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                        showProgress(false);
                        mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                        mAuthTask = null;
                        timer.cancel();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        tvUser.setError(null);
        tvPsd.setError(null);

        // Store values at the time of the login attempt.
        String phone = tvUser.getText().toString();
        String password = tvPsd.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            tvPsd.setError(getString(R.string.error_invalid_password));
            tvPsd.setText("");
            focusView = tvPsd;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(phone)) {
            tvUser.setError(getString(R.string.error_field_required));
            focusView = tvUser;
            cancel = true;
        } else if (!isPhoneValid(phone)) {
            tvUser.setError(getString(R.string.error_invalid_email));
            focusView = tvUser;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(phone, password);
            mAuthTask.execute((Void) null);

            //请求超时时
          timer = new CountDownTimer(10000, 1000) {
                public void onTick(long millisUntilFinished) {
                }
                public void onFinish() {
                    Login.this.runOnUiThread(updateThread_Overtime);
                    if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                        showProgress(false);
                        mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                        mAuthTask = null;
                        timer.cancel();
                    }
                }
            };
            timer.start();

        }
    }

    private boolean isPhoneValid(String phone) {
        //TODO: Replace this with your own logic
         /*
          移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
          联通：130、131、132、152、155、156、185、186
          电信：133、153、180、189、（1349卫通）
          总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String num = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(phone)) {
            return false;
        } else {
            //matches():字符串是否在给定的正则表达式匹配
            return phone.matches(num);
        }
        // return phone.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() >= 6;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            //loginForm.setVisibility(show ? View.GONE : View.VISIBLE);
            loginForm.setAlpha(show ? (float) 0.3 : (float) 1);
            btLogin.setClickable(show ? false : true);
            loginForget.setClickable(show ? false : true);
            loginRegister.setClickable(show ? false : true);
            loginForm.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    //loginForm.setVisibility(show ? View.GONE : View.VISIBLE);
                    loginForm.setAlpha(show ? (float) 0.3 : (float) 1);
                    btLogin.setClickable(show ? false : true);
                    loginForget.setClickable(show ? false : true);
                    loginRegister.setClickable(show ? false : true);
                }
            });

            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
            progressBar.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });

            sheepGif.setVisibility(show ? View.VISIBLE : View.GONE);
            sheepGif.setMovieResource(R.raw.sheep);

            textViewLoading.setVisibility(show ? View.VISIBLE : View.GONE);
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            loginForm.setAlpha(show ? (float) 0.3 : (float) 1);
            btLogin.setClickable(show ? false : true);
            loginForget.setClickable(show ? false : true);
            loginRegister.setClickable(show ? false : true);

            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
            sheepGif.setVisibility(show ? View.VISIBLE : View.GONE);
            textViewLoading.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    private boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, String> {

        private final String mPhone;
        private final String mPassword;

        UserLoginTask(String phone, String password) {
            mPhone = phone;
            mPassword = password;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (!isNetWorkConnected(getApplicationContext())) {
                Toast.makeText(getApplicationContext(), "请求失败,请检查网络", Toast.LENGTH_LONG).show();
            }

        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            String result = null;
            OkHttpClient client = new OkHttpClient();
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("phone", mPhone);
            builder.add("password", mPassword);

            RequestBody body = builder.build();
            Request request = new Request.Builder()
                    .url(Constanct.DOMAIN+"common/login")
                    .post(body)
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
                result = response.body().string();

            } catch (IOException e) {
                e.printStackTrace();
            }

            return result;
        }


        @Override
        protected void onPostExecute(String s) {
            if (mAuthTask != null && mAuthTask.getStatus() == AsyncTask.Status.RUNNING) {
                showProgress(false);
                mAuthTask.cancel(true); // 如果Task还在运行，则先取消它
                mAuthTask = null;
                timer.cancel();
            }
            // Toast.makeText(getApplicationContext(),"test",Toast.LENGTH_LONG).show();
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONObject jsonObject2 = new JSONObject(jsonObject.get("resultData").toString());

                switch (Integer.parseInt(jsonObject2.get("code").toString())) {
                    case 200:
                        Toast.makeText(getApplicationContext(), "" + jsonObject2.get("message"), Toast.LENGTH_SHORT).show();
                        Constanct.USER_TOKEN = jsonObject2.get("token").toString();
                        Constanct.USER_PHONE = jsonObject2.get("username").toString();
                        startActivity(new Intent(getApplication(), MainActivity.class));
                        finish();
                        break;
                    case 201:
                        mAuthTask = null;
                        showProgress(false);
                        tvUser.setError(getString(R.string.error_field_format));
                        break;
                    case 202:
                        mAuthTask = null;
                        showProgress(false);
                        tvUser.setError(getString(R.string.error_invalid_phone));
                        break;
                    case 203:
                        mAuthTask = null;
                        showProgress(false);
                        tvPsd.setError(getString(R.string.error_incorrect_password));
                        break;
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onPostExecute(s);
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}
